<template>
    <div style="height: calc(100vh - 60px) ;display: block;">
        <!-- 选项 -->
        <div>
            <h1 style="margin: 0; padding: 0 20px;">单个新增</h1>
            <div class='simple_add_div' style="padding-top: 10px; padding-left: 30px;font-size: 17px;">
                <label>考试:</label>
                <el-select v-model="examValue1" placeholder="Select" size="small" style="width: 150px;" filterable>
                    <el-option v-for="item in examOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <label>班级:</label>
                <el-select v-model="classValue1" placeholder="Select" size="small" style="width: 150px;" filterable>
                    <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <label>学号:</label><el-input v-model="stuNum" style="width: 80px;height: 22px;"
                    placeholder="Please input" />
                <label>姓名:</label><el-input v-model="stuName" style="width: 80px;height: 22px;"
                    placeholder="Please input" />
                <label>科目:</label><el-input v-model="subjectName" style="width: 80px;height: 22px;"
                    placeholder="Please input" />
                <label>得分:</label><el-input-number v-model="score" size="small" :precision="1" :step="0.1" :min="0"
                    style="width: 85px;" />
                <label>班次:</label><el-input-number v-model="classRank" size="small" :min="1" :step="1"
                    style="width: 80px;" />
                <label>校次:</label><el-input-number v-model="schRank" size="small" :min="1" :step="1"
                    style="width: 85px;" />
                <el-button style="margin-left: 40px;" type="success" size="small" @click="submitAdd">提交</el-button>
            </div>
        </div>
        <div style="height: 200px; ">
            <h1 style="margin-top: 50px; padding: 0 20px;">批量导入</h1>
            <div style="padding-bottom: 20px; padding-left: 50px;">
                <label>考试:</label>
                <el-select v-model="examValue2" placeholder="Select" size="small" style="width: 150px;" filterable>
                    <el-option v-for="item in examOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <label style="margin-left: 20px;">班级:</label>
                <el-select v-model="classValue2" placeholder="Select" size="small" style="width: 150px;" filterable
                    :on-change="handleChange" v-model:file-list="fileList">
                    <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-button style="margin-left: 40px;" type="success" size="default" @click="submitUpload">提交</el-button>
            </div>
            <el-upload style="width: 500px;height: 110px; margin-left: 60px;" :on-remove="handleRemove" :limit="1"
                :on-exceed="handleExceed" :auto-upload="false" :on-change="handleChange" v-model:file-list="fileList"
                accept=".xlsx,.xls,.XLSX,.XLS" ref="uploadRef">
                <template #trigger>
                    <el-button type="primary">选择文件</el-button>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        xlsx 格式文件,大小不超过500KB.
                    </div>
                </template>
            </el-upload>
        </div>
        <el-table :data="tableData" border height="calc(100vh - 400px)" style="width: 97%; margin: 0px auto;"
            header-align="center" align="center" v-if="tableData.length!=null && tableData.length>0">
            <el-table-column :prop="item" :label="item" :index="item.序号" v-for="(item,index) in tableTitle"
                :fixed="index < 3" show-overflow-tooltip />
        </el-table>
    </div>
</template>

<script lang="ts" setup>
    import { ref, onMounted } from 'vue'
    import { ElMessage } from 'element-plus';
    import type { UploadProps, UploadUserFile } from 'element-plus';
    import * as XLSX from 'xlsx';
    import { List } from 'echarts';
    import axios from '../utils/http';

    const stuNum = ref('')
    const stuName = ref('')
    const subjectName = ref('')
    const score = ref(0)
    const classRank = ref(1)
    const schRank = ref(1)

    const examOptions = ref([])
    const examValue1 = ref(0)
    const examValue2 = ref(0)

    const classOptions = ref([])
    const classValue1 = ref(0)
    const classValue2 = ref(0)

    const fileList = ref([]);

    const uploadRef = ref(null);
    const handleChange : UploadProps['onChange'] = (file, files) => {
        let fileContent = file.raw;
        const fileName = file.name;
        const fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
        if (fileContent) {
            if (fileType === 'xlsx' || fileType === 'xls') {
                importfile(file);
            } else {
                ElMessage({
                    type: 'error',
                    message: '附件格式错误，请重新上传！'
                })
                uploadRef.value.clearFiles();
            }
        } else {
            ElMessage({
                type: 'warning',
                message: '请上传附件！'
            });
        }
    }

    const handleExceed : UploadProps['onExceed'] = (files) => {
        ElMessage({
            type: 'warning',
            message: `最多选择1个文件`
        });
    }

    const handleRemove : UploadProps['onRemove'] = (file, uploadFiles) => {
        // console.log('移除文件')
        tableData.value = [];
        tableTitle.value = [];
    }

    // 单个提交
    const submitAdd = () => {
        if (stuNum.value == '' || stuName.value == '' || subjectName.value == '') {
            ElMessage({ type: 'error', message: '请填写学号，姓名，科目' })
            return;
        }

        axios.post('/score/add', {
            classNum: classValue1.value,
            examNum: examValue1.value,
            stuNum: stuNum.value,
            stuName: stuName.value,
            subjectName: subjectName.value,
            score: score.value,
            schRank: schRank.value,
            classRank: classRank.value
        }).then(res => {
            if (res.code == 200) {
                ElMessage({ type: 'success', message: '单条数据新增成功' })
            } else if (res.code == 500) {
                ElMessage({ type: 'error', message: res.msg })
            } else {
                ElMessage({ type: 'warning', message: res.msg })
            }
        })
    }

    // 批量提交
    const submitUpload = () => {
        // console.log('提交')
        if (tableData.value.length == 0) {
            ElMessage({ type: 'warning', message: '请先导入数据' });
            return;
        }

        const studentList = [];
        const subjects = tableTitle.value.filter(s => s.indexOf("得分") != -1);

        tableData.value.forEach(row => {
            const examAddBatchStudent = { stuNum: row['准考证号'], stuName: row['姓名'] };
            const scores = [];

            subjects.forEach(res => {
                const subjectName = res.substring(0, 2);
                scores[scores.length] = {
                    subjectName: subjectName,
                    score: isNaN(Number(row[subjectName + '得分'])) ? 0 : row[subjectName + '得分'],
                    schRank: isNaN(Number(row[subjectName + '校次'])) ? 0 : row[subjectName + '校次'],
                    classRank: isNaN(Number(row[subjectName + '班次'])) ? 0 : row[subjectName + '班次'],
                };
            })

            examAddBatchStudent['scores'] = scores;
            studentList[studentList.length] = examAddBatchStudent;
        });

        // console.log('studentList', studentList)
        
        axios.post('/exam/addBatch', {
            classcNum: classValue2.value,
            examNum: examValue2.value,
            students: studentList
        }).then(res => {
            if (res.code == 200) {
                ElMessage({ type: 'success', message: '数据批量新增成功' })
                tableData.value = [];
                tableTitle.value = [];
            } else if (res.code == 500) {
                ElMessage({ type: 'error', message: res.msg })
            } else {
                ElMessage({ type: 'warning', message: res.msg })
                tableData.value = [];
                tableTitle.value = [];
            }
        })
    }

    const tableData = ref<Object[]>([]);
    const tableTitle = ref<Object[]>([]);

    // 把文件按照二进制进行读取
    function readFile(file) {
        return new Promise((resolve) => {
            let reader = new FileReader();
            reader.readAsBinaryString(file.raw);
            reader.onload = (ev) => {
                resolve(ev.target.result);
            };
        });
    }
    const importfile = async (file) => {
        let data = await readFile(file);
        // 将得到的二进制转化一下
        let workbook = XLSX.read(data, { type: "binary" });
        //打印的workbook如图所示:https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8587ef9092424bcfb02d75d5513333ef~tplv-k3u1fbpfcp-watermark.image?
        // console.log("workbook", workbook); //这里就是可读取的文件了
        // 最后把数据转成json格式的
        let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //这里是表格的名字,这里取第一个表格,1就是第二个表格数据
        //打印的worksheet如图所示:https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a3de2e1f5b6c490faadc76604193d0ab~tplv-k3u1fbpfcp-watermark.image?
        // console.log("worksheet", worksheet);
        //将得到的worksheet转化为json格式
        // data = XLSX.utils.sheet_to_json(worksheet, { range: 1 });

        let sheet = workbook.Sheets[workbook.SheetNames[0]];
        const range = XLSX.utils.decode_range(sheet['!ref'])
        let allCells = []
        for (let rowIndex = range.s.r; rowIndex <= range.e.r; ++rowIndex) {
            let newRow = []
            allCells.push(newRow)
            for (let colIndex = range.s.c; colIndex <= range.e.c; ++colIndex) {
                const cell = sheet[XLSX.utils.encode_cell({
                    c: colIndex,
                    r: rowIndex
                })]
                let cellContent = ''
                if (cell && cell.t) {
                    cellContent = XLSX.utils.format_cell(cell)
                }
                newRow.push(cellContent)
            }
        }
        // console.log('allCells', allCells)
        handleData(allCells);

    }

    const handleData = (data) => {
        try {
            // console.log(data)
            // 文件从第4行开始才是数据
            if (data.length < 4) {
                ElMessage({ type: 'error', message: '数据格式异常' })
                return;
            }
            tableTitle.value = [];
            tableData.value = [];

            // 第一行 解析标题
            let titleList = data[1];
            for (let i = 0; i < titleList.length; i++) {
                if (titleList[i] == '班次' || titleList[i] == '校次') {
                    if (titleList[i - 1] == '班次' || titleList[i - 1] == '校次') {
                        tableTitle.value.push(titleList[i - 2] + titleList[i].substring(0, 2));
                    } else {
                        tableTitle.value.push(titleList[i - 1] + titleList[i].substring(0, 2));
                    }
                } else if (titleList[i] == '序号' || titleList[i] == '姓名' || titleList[i] == '准考证号') {
                    tableTitle.value.push(titleList[i]);
                } else {
                    tableTitle.value.push(titleList[i].substring(0, 2) + '得分');
                }
            }
            console.log('tableTitle', tableTitle)


            for (let i = 3; i < data.length; i++) {
                let map = {};
                for (let j = 0; j < data[i].length; j++) {
                    map[tableTitle.value[j]] = data[i][j];
                }
                tableData.value.push(map);
            }

            console.log('tableData', tableData)

        } catch (e) {
            console.error(e)
            ElMessage({ type: 'error', message: '数据导入异常，请检查数据格式' });
        }
    }

    onMounted(() => {
        //初始化班级和考试选项
        axios.get('/classc/list').then(r => {
            r.data.forEach(item => {
                classOptions.value.push({ value: item.classNum, label: item.className });
            });
            classValue1.value = classValue2.value = classOptions.value[0].value;
        });

        axios.post('/exam/page', {
            "size": 20,
            "current": 1
        }).then(r => {
            r.data.records.forEach(item => {
                examOptions.value.push({ value: item.examNum, label: item.examName });
            });
            examValue1.value = examValue2.value = examOptions.value[0].value;
        });
    })
</script>

<style>
    .simple_add_div label {
        margin-left: 20px;
    }

    .el-table .cell {
        width: 100px;
    }
</style>